﻿using System.Diagnostics;
using DataAcquisition.Main.Services;
using NetTaste;
using Sunny.UI;
using Vanara.PInvoke;
using WinFormium;
using WinFormium.Forms;
using static Vanara.PInvoke.UxTheme;

namespace DataAcquisition
{
    internal class IndexFormium : Formium
    {
        #region 属性
        /// <summary>
        /// 数据库状态
        /// </summary>
        private bool DataBaseState = false;

        /// <summary>
        /// 开始采集
        /// </summary>
        private bool StartState = false;

        /// <summary>工程
        /// 
        /// </summary>
        public ProjectItem projectItem;

        /// <summary>模板
        /// 
        /// </summary>
        public Template template;

        /// <summary>
        /// 当前点
        /// </summary>
        private DevicePoint point;

        /// <summary>
        /// 当前试压记录
        /// </summary>
        private TestRecord testRecord;

        /// <summary>
        /// 曲线图片路径
        /// </summary>
        static string ChartImagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");

        /// <summary>阶段
        /// 
        /// </summary>
        List<string> StageList = new List<string>();

        /// <summary>
        /// 当前阶段
        /// </summary>
        string CurrentStage = string.Empty;

        /// <summary> 起步阶段压力
        /// 
        /// </summary>
        double StartStagePressure;

        /// <summary> 起步阶段压力上限
        /// 
        /// </summary>
        double StartStagePressureMax = 0;

        /// <summary> 起步阶段压力下限
        /// 
        /// </summary>
        double StartStagePressureMin = 0;

        /// <summary>起步阶段总时间
        /// 单位s
        /// </summary>
        int StartStageTimeInterval = 20;

        /// <summary>当前步阶段剩余时间
        /// 单位s
        /// </summary>
        int StartStageTime = 20;

        /// <summary>起步阶段保持
        /// 
        /// </summary>
        bool StartStageHolding = false;

        /// <summary> 保持阶段压力
        /// 
        /// </summary>
        double HoldingStagePressure;

        /// <summary> 保持阶段压力上限
        /// 
        /// </summary>
        double HoldingStagePressureMax = 0;

        /// <summary> 保持阶段压力下限
        /// 
        /// </summary>
        double HoldingStagePressureMin = 0;

        /// <summary> 保持阶段时间
        /// 单位s
        /// </summary>
        int HoldingStageTimeInterval = 0;

        /// <summary> 保持阶段时间剩余
        /// 单位s
        /// </summary>
        int HoldingStageTime = 0;

        /// <summary> 保持阶段错误
        /// 
        /// </summary>
        bool HoldingStageError;

        /// <summary> 保持阶段错误次数
        /// 
        /// </summary>
        int HoldStageErrorTimes = 0;

        /// <summary> 保持阶段结果
        /// 
        /// </summary>
        string HoldStageResult = string.Empty;

        /// <summary>
        /// 采集点列表
        /// </summary>
        private List<double> PointList = new List<double>();

        /// <summary>
        /// 播报
        /// </summary>
        private BroadcastServices Broad = new BroadcastServices();

        /// <summary>
        /// modbus
        /// </summary>
        private ModbusServices Modbus = new ModbusServices();

        /// <summary>主风扇
        /// 
        /// </summary>
        private bool MainFanState;

        /// <summary>主压力
        /// 
        /// </summary>
        private double MainPressure = 0;

        /// <summary>主机箱温度
        /// 
        /// </summary>
        private double MainMachineTemplature = 0;

        /// <summary>主环境温度
        /// 
        /// </summary>
        private double MainEnviromentTemplature = 0;

        /// <summary>主介质温度
        /// 
        /// </summary>
        private double MainMediumTemplature = 0;

        /// <summary> 近端压力错误
        /// 
        /// </summary>
        private bool MainPressureError;

        /// <summary> 近端温度错误
        /// 
        /// </summary>
        private bool MainTemplatureError;

        /// <summary>远端风扇
        /// 
        /// </summary>
        private bool RemoteFanState;

        /// <summary>远端压力
        /// 
        /// </summary>
        private double RemotePressure = 0;

        /// <summary>远端机温度
        /// 
        /// </summary>
        private double RemoteMachineTemplature = 0;

        /// <summary>远端环境温度
        /// 
        /// </summary>
        private double RemoteEnviromentTemplature = 0;

        /// <summary>远端介质温度
        /// 
        /// </summary>
        private double RemoteMediumTemplature = 0;

        /// <summary> 远端压力错误
        /// 
        /// </summary>
        private bool RemotePressureError;

        /// <summary> 远端温度错误
        /// 
        /// </summary>
        private bool RemoteTemplatureError;

        /// <summary>主端时器
        /// 
        /// </summary>
        private System.Timers.Timer MainCollectTimer = new System.Timers.Timer();

        /// <summary>远端计时器
        /// 
        /// </summary>
        private System.Timers.Timer RemoteCollectTimer = new System.Timers.Timer();

        /// <summary> 播报测试信息
        /// 
        /// </summary>
        private System.Timers.Timer BroadcastTestDataTimer;

        /// <summary> 播报错误
        /// 
        /// </summary>
        private System.Timers.Timer BroadcastErrorTimer;

        /// <summary> 起步计时器
        /// 
        /// </summary>
        private System.Timers.Timer StartStageTimer;

        /// <summary> 保持阶段计时器
        /// 
        /// </summary>
        private System.Timers.Timer HoldingStageTimer;

        #endregion

        #region 自定义方法

        /// <summary> 前端Loading消息
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void LayerLoading(string msg)
        {
            string js = string.Format("loading('{0}')", msg);
            EvaluateJavaScriptAsync(js);
        }

        /// <summary> 关闭前端Loading消息
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void LayerLoadingClose()
        {
            string js = string.Format("endLoading()");
            EvaluateJavaScriptAsync(js);
        }

        /// <summary> 前端Error消息
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void LayerError(string msg)
        {
            LayerMsg(msg, 2);
        }

        /// <summary> 前端Success消息
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void LayerSuccess(string msg)
        {
            LayerMsg(msg, 1);
        }

        /// <summary>前端消息
        /// 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="icon"></param>
        private void LayerMsg(string msg, int icon)
        {
            string js = string.Format("message('{0}','{1}')", msg, icon);
            EvaluateJavaScriptAsync(js);
        }

        /// <summary>
        /// 检查数据库状态
        /// </summary>
        private bool CheckDataBaseState()
        {
            if (!DataBaseState)
            {
                LayerError("数据库连接失败，无法操作");
            }
            return DataBaseState;
        }

        /// <summary>
        /// 检查开始采集状态
        /// </summary>
        private bool CheckStartState()
        {
            if (StartState)
            {
                LayerError("已开始采集，无法操作");
            }
            return StartState;
        }

        /// <summary>注册方法
        /// 
        /// </summary>
        private void RegisterJavaScriptMessagHandler()
        {
            RegisterJavaScriptMessagHandler("ShowForm", args =>
            {
                string? data = args;
                if (data is not null)
                {
                    if (data == "ProjectSelect")
                    {
                        bool res = CheckDataBaseState();
                        if (!res)
                        {
                            return;
                        }
                        res = CheckStartState();
                        if (res)
                        {
                            return;
                        }
                        InvokeOnUIThread(() =>
                        {
                            SelectProjectForm frm = new SelectProjectForm();
                            frm.formium = this;
                            frm.Show();
                        });
                    }
                    else if (data == "AddProject")
                    {
                        bool res = CheckDataBaseState();
                        if (!res)
                        {
                            return;
                        }
                        res = CheckStartState();
                        if (res)
                        {
                            return;
                        }
                        InvokeOnUIThread(() =>
                        {
                            AddProjectForm frm = new AddProjectForm();
                            frm.Show();
                        });
                    }
                    else if (data == "AddTemplate")
                    {
                        bool res = CheckDataBaseState();
                        if (!res)
                        {
                            return;
                        }
                        res = CheckStartState();
                        if (res)
                        {
                            return;
                        }
                        InvokeOnUIThread(() =>
                        {
                            AddTemplateForm frm = new AddTemplateForm();
                            frm.Show();
                        });
                    }
                    else if (data == "Operation")
                    {
                        bool res = CheckDataBaseState();
                        if (!res)
                        {
                            return;
                        }
                        InvokeOnUIThread(() =>
                        {
                            OperationForm frm = new OperationForm();
                            frm.Show();
                        });
                    }
                    else if (data == "Report")
                    {
                        bool res = CheckDataBaseState();
                        if (!res)
                        {
                            return;
                        }
                        InvokeOnUIThread(() =>
                        {
                            LayerLoadingClose();
                            ReportForm frm = new ReportForm();
                            frm.projectItem = projectItem;
                            frm.testRecord = testRecord;
                            frm.template = template;
                            frm.chartImagePath = ChartImagePath;
                            frm.ShowDialog();
                        });
                    }
                }
            });

            RegisterJavaScriptMessagHandler("Collect", args =>
            {
                string? data = args;
                if (data is not null)
                {
                    if (data == "start")
                    {
                        bool res = CheckDataBaseState();
                        if (!res)
                        {
                            return;
                        }
                        if (projectItem is not null)
                        {
                            StartState = true;
                            MainCollectTimer.Start();
                            RemoteCollectTimer.Start();
                            BroadcastTestDataTimer.Start();
                            BroadcastErrorTimer.Start();
                            StartStageTimer.Start();
                            EvaluateJavaScriptAsync("startCollect()");
                            Broad.Broadcast("设备启动，请注意安全");
                        }
                        else
                        {
                            LayerError("请选择工程");
                        }
                    }
                    else if (data == "stop")
                    {
                        StartState = false;
                        MainCollectTimer.Stop();
                        RemoteCollectTimer.Stop();
                        BroadcastTestDataTimer.Stop();
                        BroadcastErrorTimer.Stop();
                        StartStageTimer.Stop();
                        HoldingStageTimer.Stop();
                        AddTestRecord();
                        EvaluateJavaScriptAsync("showReportButton()"); 
                    }
                }
            });

            RegisterJavaScriptMessagHandler("SaveDataPoint", args =>
            {
                string? data = args;
                if (data is not null)
                {
                    string[] datas = data.Split(',');
                    
                }
            });

            RegisterJavaScriptMessagHandler("SaveImage", args =>
            {
                string? data = args;
                if (data is not null)
                {
                    string name = string.Format("{0}-{1}.png",testRecord.number,projectItem.Number);
                    Tool.Base64ToImage(data, ChartImagePath, name);
                }
            });

            RegisterJavaScriptMessagHandler("Report", args =>
            {
                bool res = CheckDataBaseState();
                if (!res)
                {
                    return;
                }
                InvokeOnUIThread(() =>
                {
                    LayerLoadingClose();
                    ReportForm frm = new ReportForm();
                    frm.projectItem = projectItem;
                    frm.testRecord = testRecord;
                    frm.template = template;
                    frm.chartImagePath = ChartImagePath;
                    frm.edit = true;
                    frm.ShowDialog();
                });
            });
        }

        /// <summary>
        /// 设置服务
        /// </summary>
        /// <param name="name"></param>
        private void SetupServices()
        {
            string code = RegisterClass.ReadSetting("", "Code", "-1");
            Debug.WriteLine(code);

            Task.Run(() => {
                LayerLoading("加载设备...");
                Broad.Setup();
                Modbus.Setup();
                LayerLoadingClose();
                if (Config.BroadcastStart)
                {
                    Broad.Broadcast(Config.BroadcastStartMessage);
                }
            });
        }

        /// <summary>刷新工程信息
        /// 
        /// </summary>
        public void ReloadProjectInfo()
        {
            if (projectItem is not null)
            {
                Dictionary<string, System.Object> where = new Dictionary<string, System.Object>();
                where["number"] = projectItem.TemplateID;
                List<Template> list = SqlHelper.Inquireable<Template>(where);
                if (list.Count == 0)
                {
                    string data = string.Format("【{0}】编号的模板不存在", where["number"]);
                    MessageBox.Show(data);
                    projectItem = null;
                }
                else
                {
                    template = list[0];
                    string data = string.Format("updateProjectInfo('{0}','{1}')", projectItem.Number, projectItem.Name);
                    EvaluateJavaScriptAsync(data);

                    double pressureRange = Config.PressRange;
                    if (!Config.PressFixedRange)
                    {
                        string? manometer_range = projectItem.ManometerRange;
                        if (manometer_range is not null)
                        {
                            string[] ranges = manometer_range.Split('-');
                            if (ranges.Length > 1)
                            {
                                pressureRange = ranges[1].ToDouble();
                            }  
                        }
                    }

                    data = string.Format("updatePressureCharRange('{0}')", Math.Round(pressureRange,0));
                    EvaluateJavaScriptAsync(data);
                    string state = "未开始";
                    if (template.FirstStagePressure > 0)
                    {
                        StageList.Add("first");
                        if (StartStagePressure == 0)
                        {
                            StartStagePressure = Math.Round(template.FirstStagePressure, 3);
                        }
                    }
                    else
                    {
                        state = "--";
                    }
                    string msg = string.Format("updateStage('#firstStage','{0}')", state);
                    EvaluateJavaScriptAsync(msg);
                    
                    if (template.SecondStagePressure > 0)
                    {
                        StageList.Add("second");
                        if (StartStagePressure == 0)
                        {
                            StartStagePressure = Math.Round(template.SecondStagePressure, 3);
                        }
                        state = "未开始";
                    }
                    else
                    {
                        state = "--";
                    }
                    msg = string.Format("updateStage('#secondStage','{0}')", state);
                    EvaluateJavaScriptAsync(msg);

                    if (template.ThirdStagePressure > 0)
                    {
                        StageList.Add("third");
                        if (StartStagePressure == 0)
                        {
                            StartStagePressure = Math.Round(template.ThirdStagePressure, 3);
                        }
                        state = "未开始";
                    }
                    else
                    {
                        state = "--";
                    }
                    msg = string.Format("updateStage('#thirdStage','{0}')", state);
                    EvaluateJavaScriptAsync(msg);

                    if (template.IntensityStagePressure > 0)
                    {
                        StageList.Add("intensity");
                        if (StartStagePressure == 0)
                        {
                            StartStagePressure = Math.Round(template.IntensityStagePressure, 3);
                        }
                        state = "未开始";
                    }
                    else
                    {
                        state = "--";
                    }
                    msg = string.Format("updateStage('#intensityStage','{0}')", state);
                    EvaluateJavaScriptAsync(msg);

                    if (template.RigorStagePressure > 0)
                    {
                        StageList.Add("rigor");
                        if (StartStagePressure == 0)
                        {
                            StartStagePressure = Math.Round(template.RigorStagePressure, 3);
                        }
                        state = "未开始";
                    }
                    else
                    {
                        state = "--";
                    }
                    msg = string.Format("updateStage('#rigorStage','{0}')", state);
                    EvaluateJavaScriptAsync(msg);
                    Log.Debug(msg);
                    CurrentStage = "start";
                }
                AddTestRecord();
            }
            else
            {
                InvokeOnUIThread(() =>
                {
                    MessageBox.Show("请重新选择工程");
                });
            }
        }

        /// <summary>
        /// 添加试压记录
        /// </summary>
        private void AddTestRecord()
        {
            if (testRecord is not null)
            {
                List<TestRecord> list = new List<TestRecord>();
                testRecord.EndTime = DateTime.Now;
                list.Add(testRecord);
                int res = SqlHelper.Updateable(list);
                Log.Debug("更新试压记录：" + res);
            }
            else
            {
                int number = DateTimeOffset.Now.ToUnixTimeSeconds().ToString().ToInt();
                DateTime start = DateTime.Now;
                TestRecord obj = new TestRecord();
                obj.number = number;
                obj.StartTime = start;
                obj.Project_ID = projectItem.ID;
                List<TestRecord> list = new List<TestRecord>();
                list.Add(obj);
                int res = SqlHelper.Insertable(list);
                Log.Debug("添加试压记录：" + res);
                testRecord = obj;
            }
        }

        private System.Timers.Timer CollectTimer()
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.AutoReset = true;//是否重复执行
            return timer;
        }

        /// <summary>
        /// 设置定时器
        /// </summary>
        private void SetupTimer()
        {
            MainCollectTimer = CollectTimer();
            MainCollectTimer.Elapsed += ReadMainRegister;

            RemoteCollectTimer = CollectTimer();
            RemoteCollectTimer.Elapsed += ReadRemoteRegister;

            int timeInterval = Config.BroadcastTestDataTimeInterval;
            BroadcastTestDataTimer = CollectTimer();
            BroadcastTestDataTimer.Interval = 1000 * timeInterval;
            BroadcastTestDataTimer.Elapsed += BroadcastTestData;

            timeInterval = Config.BroadcastRemoteErrorTimeInterval;
            BroadcastErrorTimer = CollectTimer();
            BroadcastErrorTimer.Interval = 1000 * timeInterval;
            BroadcastErrorTimer.Elapsed += BroadcastRemotError;

            StartStageTimer = CollectTimer();
            StartStageTimer.Elapsed += CheckStartStage;

            HoldingStageTimer = CollectTimer();
            HoldingStageTimer.Elapsed += CheckHoldingStage;
        }

        /// <summary>播报试压数据
        /// 
        /// </summary>
        private void BroadcastTestData(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (Config.BroadcastTestData)
            {
                string mediumTemplatureString = MainMediumTemplature > 0 ? MainMediumTemplature.ToString() : string.Format("负{0}", Math.Abs(MainMediumTemplature).ToString("0.##"));
                string enviromentTemplatureString = MainEnviromentTemplature > 0 ? MainEnviromentTemplature.ToString() : string.Format("负{0}", Math.Abs(MainEnviromentTemplature).ToString("0.##"));
                string msg = string.Format("近端压力值{0}Mp，介质温度{1}度，环境温度{2}度，远端压力值{3}Mp", MainPressure.ToString("0.##"), mediumTemplatureString, enviromentTemplatureString, RemotePressure.ToString("0.##"));
                Broad.Broadcast(msg);
            }
        }

        /// <summary> 播报远端错误
        /// 
        /// </summary>
        private void BroadcastRemotError(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (Config.BroadcastRemoteError)
            {
                if (MainPressureError == true)
                {
                    Thread.Sleep(100);
                    Broad.Broadcast("近端压力采集失败");
                }
                
                if (MainTemplatureError == true)
                {
                    Thread.Sleep(100);
                    Broad.Broadcast("近端温度采集失败");
                }

                if (RemotePressureError == true)
                {
                    Thread.Sleep(100);
                    Broad.Broadcast("远端压力采集失败");
                }

                if (RemoteTemplatureError == true)
                {
                    Thread.Sleep(100);
                    Broad.Broadcast("远端温度采集失败");
                }
            }
        }
        /// <summary>读取主设备
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReadMainRegister(object? sender, System.Timers.ElapsedEventArgs e)
        {
            int sleep = 100;
            
            double result = ReadPressure("MPressure", "updateMainPressureChart");
            if (result == -999)
            {
                MainPressureError = true;
            }
            else
            {
                MainPressureError = false;
                MainPressure = result;
            }
            if (point is not null)
            {
                if (StartStagePressure > 0)
                {
                    StartStagePressureMin = Math.Round(StartStagePressure * (1 - (point.ErrorRange / 100)), 3);
                    StartStagePressureMax = Math.Round(StartStagePressure * (1 + (point.ErrorRange / 100)), 3);
                }
                else
                {
                    Log.Error("❌请注意起步压力异常❌");
                }
            }
            /*
            Thread.Sleep(sleep);
            bool[]? res = Modbus.ReadCoilsAsync("MFan", 1);
            if (res != null)
            {
                MainFanState = res[0];
                Log.Debug("主风扇状态：" + MainFanState);
            }*/

            Thread.Sleep(sleep);
            double result2 = ReadTemplature("MediumTemplature", "updateMediumTemplature");
            if (result2 != -999)
            {
                MainMediumTemplature = result2;
            }

            Thread.Sleep(sleep);
            double result3 = ReadTemplature("MEnviromentTemplature", "updateEnviromentTemplature");
            if (result3 != -999)
            {
                MainEnviromentTemplature = result3;
            }

            Thread.Sleep(sleep);
            double result4 = ReadTemplature("MachineTemplature", "updateMainBoxTemplature");
            if (result4 != -999)
            {
                MainMachineTemplature = result4;
            }

            if (result2 != -999 && result3!=-999 && result4 !=-999)
            {
                MainTemplatureError = false;
            }
            else
            {
                MainTemplatureError = true;
            }

            Thread.Sleep(sleep);
        }

        /// <summary>读取远端设备
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReadRemoteRegister(object? sender, System.Timers.ElapsedEventArgs e)
        {
            /*
            int sleep = 100;

            bool[]? res = Modbus.ReadCoilsAsync("RFan", 1);
            if (res != null)
            {
                MainFanState = res[0];
                Log.Debug("远端风扇状态：" + MainFanState);
            }

            Thread.Sleep(sleep);
            double result = ReadPressure("RPressure", "updateRemotePressureChart");
            if (result == -999)
            {
                RemotePressureError = true;
            }
            else
            {
                RemotePressureError = false;
                RemotePressure = result;
            }

            Thread.Sleep(sleep);
            double result2 = ReadTemplature("RMachineTemplature", "updateRemoteBoxTemplature");
            if (result2 != -999)
            {
                RemoteMachineTemplature = result2;
            }

            Thread.Sleep(sleep);
            double result3 = ReadTemplature("REnviromentTemplature","");
            if (result3 != -999)
            {
                RemoteEnviromentTemplature = result3;
            }

            Thread.Sleep(sleep);
            double result4 = ReadTemplature("RMediumTemplature", "");
            if (result4 != -999)
            {
                RemoteMediumTemplature = result4;
            }

            if (result2 != -999 && result3 != -999 && result4 != -999)
            {
                RemoteTemplatureError = false;
            }
            else
            {
                RemoteTemplatureError = true;
            }
            Thread.Sleep(sleep);*/

            SaveDataPoint(MainPressure, MainEnviromentTemplature, MainMediumTemplature, MainMachineTemplature, RemotePressure, RemoteMediumTemplature, RemoteMachineTemplature, DateTime.Now);
        }

        /// <summary>
        /// 读取压力
        /// </summary>
        private double ReadPressure(string key, string completion)
        {
            Dictionary<string, object>? back = Modbus.ReadHoldingRegistersAsync(key);
            string alarm = "0";
            if (back != null)
            {
                ushort[] shorts = (ushort[])back["data"];

                point = (DevicePoint)back["devicePoint"];

                double outMax = point.OutMax;

                double outMin = point.OutMin;

                double rangeMax = point.RangeMax;

                double rangeMin = point.RangeMin;

                double pressure = (shorts[0] - outMin) / (outMax - outMin);
                pressure = Math.Round(pressure * (rangeMax - rangeMin) + rangeMin, 3);
                string log = string.Empty;
                if (pressure > point.AlarmHight)
                {
                    alarm = "1";
                    log = string.Format("【{0}:】【{1}】超过限高阈值【{2}】", point.Name, pressure, point.AlarmHight);
                }
                else if (pressure < point.AlarmLow)
                {
                    alarm = "1";
                    log = string.Format("【{0}:】【{1}】低于最低阈值【{2}】", point.Name, pressure, point.AlarmLow);
                }
                else
                {
                    alarm = "0";
                    log = string.Format("【{0}:】【{1}】", point.Name, pressure);
                }
                Log.Debug(log);
                if (completion.Length > 0)
                {
                    string data = string.Format("{0}('{1}','{2}')", completion,pressure, alarm);
                    EvaluateJavaScriptAsync(data);
                }
                return pressure;
            }
            else
            {
                return -999;
            }

        }

        /// <summary>
        /// 读取温度
        /// </summary>
        private double ReadTemplature(string key,string completion)
        {
            Dictionary<string, object>? back = Modbus.ReadInputRegistersAsync(key, 1);
            if (back != null)
            {
                ushort[] shorts = (ushort[])back["data"];
                DevicePoint point = (DevicePoint)back["devicePoint"];
                float temperature = (Tool.ConvertUshort(shorts[0]) / 10.0f);
                double backTemperature = Math.Round(temperature, 3);
                string log = string.Empty;
                string alarm = "0";
                if (backTemperature > point.AlarmHight)
                {
                    alarm = "1";
                    log = string.Format("【{0}】:【{1}】超过限高阈值【{2}】", point.Name, backTemperature, point.AlarmHight);
                }
                else
                {
                    alarm = "0";
                    log = string.Format("【{0}】:【{1}】", point.Name, backTemperature);
                }
                //Log.Debug(log);
                if (completion.Length > 0)
                {
                    string data = string.Format("{0}('{1}','{2}')",completion, backTemperature, alarm);
                    EvaluateJavaScriptAsync(data);
                }
                return backTemperature;
            }
            else
            {
                return -999;
            }
        }

        /// <summary> 起步阶段
        /// 
        /// </summary>
        private void CheckStartStage(object? sender, System.Timers.ElapsedEventArgs e)
        {
            string stageString = StageString(StageList[0]);
            string log = string.Empty;
            string result = "未开始";
            if ((MainPressure > StartStagePressureMax))
            {
                if ((StartStageHolding))
                {
                    HoldingStageError = true;
                }
                ReStartTimer();
                log = string.Format("当前压力【{0}】>【{1}】的标准", MainPressure, StartStagePressureMax);
                result = "压力高";
            }
            else if ((MainPressure < StartStagePressureMin))
            {
                if ((StartStageHolding))
                {
                    HoldingStageError = true;
                }

                ReStartTimer();
                log = string.Format("当前压力【{0}】<【{1}】的标准", MainPressure, StartStagePressureMin);
                result = "压力低";
            }
            else if ((MainPressure >= StartStagePressureMin) && (!StartStageHolding) && MainPressure > 0)
            {
                HoldingStageError = false;
                log = string.Format("【{0}】开始稳压【{1}】，范围：【{2}-{3}】", stageString, StartStagePressure, StartStagePressureMin, StartStagePressureMax);
                StartStageHolding = true;
                result = "采集中";
            }
            if (log.Length > 0)
            {
                Log.Debug(log);
            }

            if (StartStageHolding)
            {
                result = "采集中";
                if (StartStageTime == 0)
                {
                    if (PointList.Count == 0)
                    {
                        log = string.Format("【{0}】稳压通过。", stageString);
                        Log.Debug(log);
                    }
                    if (PointList.Count < 10)
                    {
                        PointList.Add(MainPressure);
                        log = string.Format("【{0}】采集点位数量：【{1}】", stageString,PointList.Count);
                        Log.Debug(log);
                    }
                    else
                    {
                        double sum = PointList.Sum();
                        PointList.Clear();
                        if (StageList.Count > 0)
                        {
                            StartStageTimer.Stop();
                            ReStartTimer();
                            HoldingStagePressure = Math.Round(sum / 10.0f, 3);
                            UpdateStageInfo(StageList[0], true);
                            //HoldingStageTime = StartStageTimeInterval;
                            HoldingStageTimer.Start();
                            log = string.Format("【{0}】阶段基准压力【{1}】", stageString, HoldingStagePressure);
                            Log.Debug(log);
                        }
                    }
                }
                else
                {
                    log = string.Format("【{0}】稳压剩余【{1}】s", stageString, StartStageTime);
                    Log.Debug(log);
                    if ((MainPressure >= StartStagePressureMin) && (MainPressure <= StartStagePressureMax))
                    {
                        StartStageTime--;
                    }
                    else
                    {
                        ReStartTimer();
                    }
                }
            }
            string msg = string.Format("updateStage('#{0}Stage','{1}')", StageList[0], result);
            EvaluateJavaScriptAsync(msg);
        }

        /// <summary> 保持阶段
        /// 
        /// </summary>
        private void CheckHoldingStage(object? sender, System.Timers.ElapsedEventArgs e)
        {
            string stageString = StageString(StageList[0]);
            if (HoldingStageTime == 0)
            {
                HoldStageResult = "合格";
                string msg = string.Format("{0}检测{1}，请注意安全", stageString, HoldStageResult);
                Broad.Broadcast(msg);
                msg = string.Format("updateStage('#{0}Stage','合格')", StageList[0]);
                Log.Debug(msg);
                EvaluateJavaScriptAsync(msg);
                if (StageList.Count > 1)
                {
                    Thread.Sleep(100);
                    Log.Debug(msg);
                    StageList.RemoveAt(0);
                    UpdateStageInfo(StageList[0], false);
                    HoldingStageTimer.Stop();
                    StartStageTimer.Start();
                }
                else if (StageList.Count > 0)
                {
                    StageList.RemoveAt(0);
                    if (StageList.Count == 0)
                    {
                        Log.Debug("试压阶段结束");
                        if (HoldingStageTimer is not null)
                        {
                            HoldingStageTimer.Stop();
                        }
                        StartStageTimer.Stop();
                        ReStartTimer();
                        ReHoldTimer();
                        Thread.Sleep(100);
                        Broad.Broadcast("试压检测合格，请注意安全");
                        AddTestRecord();
                    } 
                }
                else
                {
                    
                }
            }
            else
            {
                HoldingStageError = false;
                string log = string.Format("【{0}】试压剩余【{1}】", stageString, HoldingStageTime);
                Log.Debug(log);
                if (MainPressure >= HoldingStagePressureMin && MainPressure <= HoldingStagePressureMax)
                {
                    HoldingStageTime--;
                    string msg = string.Format("updateStage('#{0}Stage','{1}')", StageList[0], Tool.Secondtohms(HoldingStageTime));
                    EvaluateJavaScriptAsync(msg);
                }
                else if (MainPressure > HoldingStagePressureMax | MainPressure < HoldingStagePressureMin)
                {
                    if (HoldStageErrorTimes <= 3)
                    {
                        HoldingStageError = true;
                        HoldStageErrorTimes++;
                    }
                    else
                    {
                        HoldingStageTimer.Stop();
                        ReStartTimer();
                        ReHoldTimer();
                        StartStageTimer.Start();
                        HoldingStageError = false;
                        string msg = string.Format("updateStage('#{0}Stage','{1}')", StageList[0], "未开始");
                        EvaluateJavaScriptAsync(msg);
                    }
                }
                else
                {
                    string msg = string.Format("{0}--{1}--{2}", MainPressure, HoldingStagePressureMin, HoldingStagePressureMax);
                    Log.Debug(msg);
                }
            }
        }

        /// <summary> 更新阶段信息
        /// 
        /// </summary>
        /// <param name="stage"> 阶段</param>
        /// /// <param name="broadcast">是否播报</param>
        private void UpdateStageInfo(string stage, bool broadcast)
        {
            double pressure = 0;
            int time = 0;
            int stage_estimate = 0;
            double stage_estimate_value = 0;
            string stageString = StageString(stage);
            double tmp = 1;
            if (stage == "first")
            {
                Log.Debug("第一阶段");
                pressure = template.ThirdStagePressure;
                double multiple = 1;
                if (template.FirstStageTimeUnit == "小时")
                {
                    multiple = 60;
                }
                time = (int)(template.FirstStageTime * tmp * multiple);
                stage_estimate = template.FirstStageEstimateWay;
                stage_estimate_value = template.FirstStageEstimateValue;
            }
            else if (stage == "second")
            {
                pressure = template.SecondStagePressure;
                double multiple = 1;
                if (template.SecondStageTimeUnit == "小时")
                {
                    multiple = 60;
                }
                time = (int)(template.SecondStageTime * tmp * multiple);
                stage_estimate = template.SecondStageEstimateWay;
                stage_estimate_value = template.SecondStageEstimateValue;
            }
            else if (stage == "third")
            {
                pressure = template.ThirdStagePressure;
                double multiple = 1;
                if (template.ThirdStageTimeUnit == "小时")
                {
                    multiple = 60;
                }
                time = (int)(template.ThirdStageTime * tmp * multiple);
                stage_estimate = template.ThirdStageEstimateWay;
                stage_estimate_value = template.ThirdStageEstimateValue;
            }
            else if (stage == "intensity")
            {
                pressure = template.IntensityStagePressure;
                double multiple = 1;
                if (template.IntensityStageTimeUnit == "小时")
                {
                    multiple = 60;
                }
                time = (int)(template.IntensityStageTime * tmp * multiple);
                stage_estimate = template.IntensityStageEstimateWay;
                stage_estimate_value = template.IntensityStageEstimateValue;
            }
            else if (stage == "rigor")
            {
                pressure = template.RigorStagePressure;
                double multiple = 1;
                if (template.RigorStageTimeUnit == "小时")
                {
                    multiple = 60;
                }
                time = (int)(template.RigorStageTime * tmp * multiple);
                stage_estimate = template.RigorStageEstimateWay;
                stage_estimate_value = template.RigorStageEstimateValue;
            }
            StartStagePressure = pressure;
            //HoldingStagePressure = pressure;

            if (stage_estimate == 1) //范围
            {
                HoldingStagePressureMin = Math.Round(HoldingStagePressure * (1 - (stage_estimate_value / 100)), 3);
                HoldingStagePressureMax = Math.Round(HoldingStagePressure * (1 + (stage_estimate_value / 100)), 3);
            }
            else
            {
                HoldingStagePressureMin = Math.Round(HoldingStagePressure - stage_estimate_value, 3);
                HoldingStagePressureMax = Math.Round(HoldingStagePressure + stage_estimate_value, 3);
            }


            HoldingStageTime = time;
            HoldingStageTimeInterval = HoldingStageTime;
            if (broadcast)
            {
                string a = Tool.NumToTime(HoldingStageTime);
                string msg = string.Format("{0}{1}开始倒计时，请注意安全", stageString, a);
                Broad.Broadcast(msg);
            }
            string log = string.Format("【{0}】开始试压：【{1}】，范围【{2}-{3}】", stageString, HoldingStagePressure, HoldingStagePressureMin, HoldingStagePressureMax);
            Log.Debug(log);
        }

        private string StageString(string stage)
        {
            string stageString = "";
            if (stage == "first")
            {
                stageString = "第一阶段";
            }
            else if (stage == "second")
            {
                stageString = "第二阶段";
            }
            else if (stage == "third")
            {
                stageString = "第三阶段";
            }
            else if (stage == "intensity")
            {
                stageString = "强度实验阶段";
            }
            else if (stage == "rigor")
            {
                stageString = "严密性实验阶段";
            }
            return stageString;
        }

        /// <summary>重置起步计时器
        /// 
        /// </summary>
        private void ReStartTimer()
        {
            StartStageHolding = false;
            StartStageTime = StartStageTimeInterval;
        }

        /// <summary>重置保持计时器
        /// 
        /// </summary>
        private void ReHoldTimer()
        {
            HoldingStageTime = HoldingStageTimeInterval;
        }

        /// <summary>保存数据点位
        /// 
        /// </summary>
        private void SaveDataPoint(double mainPressure, double enviromentTemplature, double mainMediumTemplature, double mainMachineTemplature,
                                   double remotePressure, double remoteMediumTemplature, double remoteMachineTemplature, DateTime time)
        {
            if (projectItem is not null)
            {
                DataPoint point = new DataPoint();
                point.test_record_number = testRecord.number;
                point.time = time;
                point.main_pressure = mainPressure;
                point.enviroment_templature = enviromentTemplature;
                point.main_medium_templature= mainMediumTemplature;
                point.main_machine_templature = mainMachineTemplature;
                point.remote_pressure = remotePressure;
                point.time = Convert.ToDateTime(time);
                List<DataPoint> list = new List<DataPoint>();
                list.Add(point);
                int res = SqlHelper.Insertable(list);
                //Log.Debug("数据点位入库：" + res);
            }
        }
        #endregion

        #region 系统方法
        public IndexFormium()
        {
            ///不显示窗体过度动画
            EnableSplashScreen = false;
            Icon icon = new Icon("logo.ico");
            Icon = icon;
            Sizable = false;//禁止调整窗口大小
            Url = "http://dataqcquisition.app.local/Index.html";
            Loaded += IndexFormium_Loaded;
            PageLoadEnd += IndexFormium_PageLoadEnd;
            RegisterJavaScriptMessagHandler();
            SetupTimer();
        }
        protected override FormStyle ConfigureWindowStyle(WindowStyleBuilder builder)
        {
            var style = builder.UseSystemForm();
            style.TitleBar = true;
            style.DefaultAppTitle = "数据采集";
            style.Maximizable = true;
            style.WindowState = FormiumWindowState.Maximized;
            style.StartCentered = StartCenteredMode.CenterScreen;
            style.ColorMode = FormiumColorMode.Light;
            if (Screen.PrimaryScreen is not null)
            {
                style.MinimumSize = Screen.PrimaryScreen.WorkingArea.Size;
            }
            return style;
        }

        /// <summary>窗体加载完成
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IndexFormium_Loaded(object? sender, BrowserEventArgs e)
        {

        }

        /// <summary>页面加载完成
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IndexFormium_PageLoadEnd(object? sender, PageLoadEndEventArgs e)
        {
            LayerLoading("连接数据库...");
            Task.Run(() => {
                int res = 0;
                if (SqlHelper.State() == false)
                {
                    LayerError("连接数据库失败");
                    DataBaseState = false;
                }
                else
                {
                    LayerLoadingClose();
                    SetupServices();
                    DataBaseState = true;
                    res = 1;
                }
                string data = string.Format("updateDataBaseState('{0}')", res);
                EvaluateJavaScriptAsync(data);
            });
        }

        #endregion
    }
}
